<template>
    <div class="pane-con">
        <xdh-layout fixed :north="{height: 'auto'}" >
             <xdh-filter-panel title="查询条件" :model.sync="model" @on-query="handleQuery" slot="north" >
            <el-form-item label="现持证件号码" prop="passno">
                <el-input v-model="model.passno" placeholder="请填写证件号码"></el-input>
            </el-form-item>
            <el-form-item label="国籍" prop="gj">
              <el-select v-model="model.gj"  :value-key="'code'" filterable placeholder="请选择国籍"
               clearable>
                <el-option
                v-for="(item, idx) in gjList" :key="idx"
                :label="item.note"
                :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
               <el-select v-model="model.sex" clearable>
                  <el-option
                  label="全部" value="">
                  </el-option>
                  <el-option
                  label="男" value="1">
                  </el-option>
                  <el-option
                  label="女" value="2">
                  </el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="是否超期" prop="timeout">
               <el-select v-model="model.timeout" clearable>
                  <el-option
                  label="全部" value="">
                  </el-option>
                  <el-option
                  label="是" value="1">
                  </el-option>
                  <el-option
                  label="否" value="2">
                  </el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="出生日期" prop="csrq">
               <el-date-picker
               style="width:140px;"
                     size="mini"
                      v-model="model.startBirthday"
                      placeholder="开始日期"
                      :value-format="'yyyy-MM-dd'"
                      :default-value="defaultBirthday">
                    </el-date-picker>
                    &nbsp;&nbsp;至&nbsp;&nbsp;
                      <el-date-picker
                          style="width:140px;"
                     size="mini"
                      v-model="model.endBirthday"
                      :value-format="'yyyy-MM-dd'"
                      placeholder="结束日期"
                      :default-value="defaultBirthday">
                    </el-date-picker>
            </el-form-item>
              <el-form-item label="签证办理时间" prop="timeRange">
                  <el-date-picker
               style="width:140px;"
                     size="mini"
                      :value-format="'yyyy-MM-dd'"
                      v-model="model.startDate"
                      placeholder="开始日期"
                      :default-value="defaultSignday">
                    </el-date-picker>
                    &nbsp;&nbsp;至&nbsp;&nbsp;
                      <el-date-picker
                          style="width:140px;"
                     size="mini"
                      :value-format="'yyyy-MM-dd'"
                      v-model="model.endDate"
                      placeholder="结束日期"
                      :default-value="defaultSignday">
                    </el-date-picker>
            </el-form-item>
            <el-form-item label="境内居住地行政区划及派出所" prop="caddrareacode">
                <el-cascader :options="mix_xzqhList"
                v-model="model.jn"
                filterable
                 :props="mix_propMap"
                 expand-trigger="click"
                 change-on-select
                 clearable>
                </el-cascader>
            </el-form-item>
              <el-form-item label="工作地行政区划及派出所" prop="caddrareacode">
                <el-cascader :options="mix_xzqhList"
                v-model="model.gzd"
                filterable
                 :props="mix_propMap"
                 size="small"
                 expand-trigger="click"
                 change-on-select
                 clearable>
                </el-cascader>
            </el-form-item>
          
            </xdh-filter-panel>
            <xdh-list-panel :load="loadData" :state="state" fit ref="listPanel"
            :sizes="pageSizes" :size="20">
            <template class="submit-btns" slot="tool">
                <input type="file" ref="uploadInput" style="display:none" 
                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
                @change="fileUploaded"/>
                <el-button type="primary" size="small" class="btn"  @click="upload()" v-auth="2" v-if="status === 'send'">导入excel</el-button>
                <el-button type="primary" size="small" class="btn" v-if="showSendAll && status === 'send'" @click="sendMulti('all')">一键下发</el-button>
                <el-button type="primary" size="small" class="btn" v-if="!showSendAll && status === 'send'" @click="sendMulti()">下发已选项</el-button>
            </template>
                <template slot-scope="scope">
                    <el-table :data="state.list" border  
                    :height="scope.height" selectable
                    @selection-change="selectionChange"
                    :row-class-name="highlightRow"
                    >
                    <el-table-column label="全选" prop="check" type="selection" v-if="status === 'send'">
                    </el-table-column>
                    <el-table-column type="index" :label="'序号'" :index="calcIndex" :width="50">

                    </el-table-column>
                    <el-table-column label="国家地区" prop="ccountry" :min-width="90">
                    </el-table-column>
                    <el-table-column label="英文姓名" prop="enname" show-overflow-tooltip :min-width="150"></el-table-column>
                    <el-table-column label="性别" prop="csex" :min-width="60"></el-table-column>
                    <el-table-column label="出生日期" prop="birthday" :min-width="100">
                      <template slot-scope="scope">
                         {{scope.row.birthday | dateFormat}}
                      </template>
                    </el-table-column>
                    <el-table-column label="现持证件号码" prop="passno" :min-width="90"></el-table-column>
                    <el-table-column label="所持证件有效期至" prop="signvali" :min-width="100">
                           <template slot-scope="scope">
                         {{scope.row.signvali | dateFormat}}
                      </template>
                    </el-table-column>
                    <el-table-column label="签证/居留许可号码" prop="signno" :min-width="90"></el-table-column>
                    <el-table-column label="签发日期" prop="signdate" :min-width="100">
                      <template slot-scope="scope">
                         {{scope.row.signdate | dateFormat}}
                      </template>
                    </el-table-column>
                    <el-table-column label="境内居住地行政区划" prop="caddrareacode" show-overflow-tooltip :min-width="150"></el-table-column>
                    <el-table-column label="境内居住地派出所" prop="caddrpolicecode" show-overflow-tooltip :min-width="150"></el-table-column>
                    <el-table-column label="操作" :width="operWidth[status]" fixed="right">
                           <template slot-scope="scope">
                              <el-button @click="view(scope.row)" type="default" size="mini">
                                  <i class="iconfont icon-visible"></i>
                                  查看</el-button>
                              <el-button type="primary" size="mini" @click="send(scope.row)" v-if="status ==='send'">
                                        <i class="iconfont icon-share"></i>
                                  下发</el-button>
                          
                            </template>
                    </el-table-column>
                    </el-table>
                </template>
            </xdh-list-panel>
        </xdh-layout>
        <person-detail :visible="personDialog" :row-data="personData" @close="personDialog = false"></person-detail>
        <send-option-dialog :visible="optionDialog" 
        :data="personData" :mode="optionMode"
         @close="optionDialog = false"
         :after-choose="optionChoose"></send-option-dialog>
    </div>
</template>
<script>
import XdhFilterPanel from '@/widgets/xdh-filter-panel';
import XdhListPanel from '@/widgets/xdh-list-panel';
import XdhLayout from '@/widgets/xdh-layout';
import PersonDetail from '@/components/common/personDetail';
import SendOptionDialog from '@/components/common/sendOptionDialog';

import taskMixin from '@/base/mixin/fvisas';
import pcsMixin from '@/base/mixin/cgabunits';
import checktaskMixin from '@/base/mixin/checktasks';
import policeMixin from '@/helper/police'
import countryMixin from '@/base/mixin/fcountrys';

import timePickerOptions from '@/helper/timePickerOptions';
import date from '@/utils/date';
import { UPLOAD_FILE } from '@/config';
import axios from '@/utils/axios';

export default {
  mixins: [taskMixin, pcsMixin, checktaskMixin, countryMixin, policeMixin],
  components: {
    XdhFilterPanel,
    XdhListPanel,
    XdhLayout,
    PersonDetail,
    SendOptionDialog
  },
  props: {
    status: {
      type: String,
      default: 'send'
    }
  },
  data() {
    return {
      selectedIds: '',
      timePickerOptions,
      showSendAll: true,
      optionDialog: false,
      optionChoose: null,
      optionMode: 'batch',
      personDialog: false,
      personData: null,
      pageSizes: [20, 50, 100, 500],
      operWidth: {
        send: 180,
        notFeedback: 100,
        feedback: 100
      },
      defaultBirthday: new Date(2000, 0, 1),
      defaultSignday: new Date(),
      gjList: [],
      stateMap: {
        send: 0,
        notFeedback: 1,
        feedback: 2
      },
      state: {
        total: 0,
        list: []
      },
      model: {
        passno: '',
        jn: [],
        gzd: [],
        startDate: '',
        endDate: '',
        startBirthday: '',
        endBirthday: '',
        sex: '',
        country: '',
        timeout: ''
      },
      pageInfo: {
        page: 1,
        limit: 20
      }
    };
  },
  filters: {
    dateFormat(val) {
      if (!val) {
        return '-';
      }
      let y = val.slice(0, 4);
      let m = parseInt(val.slice(4, 6)) - 1;
      let d = val.slice(6, 8);
      return date(new Date(y, m, d), 'yyyy-MM-dd');
    }
  },
  watch: {
    status(val) {
      this.$refs.listPanel.reload();
    }
  },
  methods: {
    date,
    calcIndex(index) {
       return index + (this.pageInfo.page - 1) * this.pageInfo.limit + 1;
    },
    view(row) {
      this.personDialog = true;
      this.personData = { ...row };
    },
    getSendOption(type, row) {
      this.optionDialog = true;
      if (row) {
        this.personData = { ...row };
      }
      this.optionMode = type;
      return new Promise((resolve, reject) => {
        this.optionChoose = {
          resolve: resolve,
          reject: reject
        };
      });
    },
    send(row) {
      this.getSendOption('single', row).then(res => {
        if (res) {
          let postData = Object.assign({}, { ids: row.pkValue }, res);
          this.addChecktasks(postData).then(res => {
            if (res) {
              this.sendSuccess();
            }
          });
        }
      });
    },
    sendMulti(isAll) {
      let ids = '';
      if (isAll) {
        ids = this.state.list
          .map(r => {
            return r.pkValue;
          })
          .join(',');
      } else {
        ids = this.selectedIds;
      }
      this.getSendOption('batch').then(res => {
        let postData = Object.assign({}, { ids: ids }, res);
        this.addChecktasks(postData).then(res => {
          if (res) {
            this.sendSuccess();
          }
        });
      });
    },
    sendSuccess() {
      this.$message({
        type: 'success',
        message: '下发成功'
      });
      this.$refs.listPanel.reload();
    },
    highlightRow(obj) {
      if (obj.row.csex === '男') {
        return 'high-light';
      } else {
        return '';
      }
    },
    upload() {
      this.$refs.uploadInput.click();
    },
    fileUploaded(elem) {
      let files = elem.target.files[0];
      let formData = new FormData();
      formData.append('file', files);
      axios({
        headers: {
          'Content-Type': 'application/octet/stream'
        },
        url: UPLOAD_FILE,
        data: formData,
        method: 'post'
      })
        .then(res => {
          if (res.data.code === 0) {
            this.$refs.listPanel.reload();
            this.$message({
              type: 'success',
              message: `上传成功`
            });
          }
        })
        .catch(e => {
          this.$message({
            type: 'warning',
            message: `上传失败:${e}`
          });
        });
    },
    loadData(page, limit) {
      this.pageInfo.page = page;
      this.pageInfo.limit = limit;
      let query = Object.assign({}, this.model, {
        state: this.stateMap[this.status],
        page: page,
        limit: limit
      });
      if(query.gj) {
        query.country = query.gj.code;
      }
      delete query.jn;
      delete query.gzd;
      delete query.gj;
      for (var i in query) {
        if (!query[i] && query[i] !== 0) {
          delete query[i];
        }
      }
      return this.fetchFvisas(query).then(res => {
        this.state = res;
        if (this.pageSizes[this.pageSizes.length - 1] < this.state.total) {
          this.pageSizes.push(this.state.total);
        }
      });
    },
    selectionChange(obj) {
      this.selectedIds = obj
        .map(r => {
          return r.pkValue;
        })
        .join(',');
      if (obj.length === 0) {
        this.showSendAll = true;
      } else {
        this.showSendAll = false;
      }
    },
    handleQuery(query) {
      if (query.jn) {
        this.model.addrpolicecode = query.jn[0] || '';
        this.model.addrareacode = query.jn[1] || '';
      } else {
        this.model.addrpolicecode = '';
        this.model.addrareacode = '';
      }
      if (query.gzd) {
        this.model.workareacode = query.gzd[0] || '';
        this.model.workpolice = query.gzd[1] || '';
      } else {
        this.model.workareacode = '';
        this.model.workpolice = '';
      }
      this.$refs.listPanel.reload();
    }
  },
  created() {
    this.getCountryList({}).then(res => {
      this.gjList = res;
    });
    this.mix_getPcs();
  }
};
</script>
<style  type='text/scss' lang='scss' scoped>
.pane-con {
  height: calc(100% - 30px);
  .submit-btns {
    height: 50px;
    text-align: center;
    padding: 15px;
  }
}
</style>
<style type='text/scss' lang='scss'>
$highlightColor: rgba(149, 190, 234, 0.6);
.pane-con {
  .high-light {
    background-color: $highlightColor;
    // color: #ff752f;
  }
  .high-light.hover-row > td {
    background-color: $highlightColor;
  }
}
</style>